package com.zlm.controller;


import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码请求controller(前后分离的 因此需要返回base64)
 */

@RestController
public class VerifyCodeController {

    @Resource
    private Producer producer;

    @GetMapping("/vc.jpg")
    public String verifyCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {

        // 生成验证码
        String verifyCode = producer.createText();
        System.out.println("验证码为：" + verifyCode);

        // 验证码保存在session里面(当然后面肯定是保存在redis里面的)
        session.setAttribute("verifyCode", verifyCode);

        // 设置图片类型(在前后分离这里不需要设置)
//        response.setContentType("image/png");
        // 生成图片
        BufferedImage bi = producer.createImage(verifyCode);

        //2.写入内存
        // Byte数组
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "png", fos);
        //3.生成 base64
        return Base64.encodeBase64String(fos.toByteArray());
    }
}
